<template>
  <div class="page-container">
    <!-- 头部操作栏 -->
    <div class="header">
      <el-form :model="filterParams" inline class="filter-form">
        <el-form-item label="用户名">
          <el-input
            v-model="filterParams.username"
            placeholder="请输入用户名"
            clearable
            style="width: 160px;"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="filterParams.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 180px;"
          />
        </el-form-item>
        <el-form-item label="角色" style="width: 180px;">
          <el-select
            v-model="filterParams.roleId"
            placeholder="请选择角色"
            clearable
          >
            <el-option label="全部" :value="null" />
            <el-option label="普通用户" :value="3" />
            <el-option label="家庭管理员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="家庭编号">
          <el-input-number
            v-model="filterParams.houseId"
            :min="1"
            controls-position="right"
            placeholder="家庭编号"
            clearable
            style="width: 180px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchUsers">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="users"
        height="calc(100vh - 120px)"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="username"
          label="用户名"
          min-width="120"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="roleId"
          label="角色"
          width="100"
          align="center"
          header-align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.roleId === 2 ? 'success' : 'info'">
              {{ row.roleId === 2 ? '家庭管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="houseId"
          label="房屋ID"
          width="100"
          align="center"
          header-align="center"
        />
        <el-table-column
          label="创建时间"
          width="180"
          align="center"
          header-align="center"
        >
          <template #default="{ row }">
            {{ new Date(row.createTime).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="150"
          fixed="right"
          align="center"
          header-align="center"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.email)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="500px"
      :close-on-click-modal="false"
      key="editDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editUser"
        :rules="eidtRules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item label="用户名" prop="username" required>
          <el-input v-model="editUser.username" placeholder="2-16位字符" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="editUser.email" placeholder="有效邮箱地址" disabled />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="editUser.roleId">
                <el-option label="普通用户" :value="3" />
                <el-option label="家庭管理员" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房屋ID" prop="houseId">
              <el-input-number v-model="editUser.houseId" :min="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditUser">保存修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { userList, userUpdate, userDel } from '@/api/account';
import { ElMessage, ElMessageBox } from 'element-plus';

// 用户列表数据
const users = ref([]);
const loading = ref(false);

// 筛选条件
const filterParams = ref({
  username: '',
  email: '',
  roleId: null,
  houseId: null
});

// 编辑用户弹窗相关
const editDialogVisible = ref(false);
const editUser = ref({
  username: '',
  email: '',
  roleId: null,
  houseId: null,
  account: 0
});

// 表单验证规则
const eidtRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  houseId: [{ required: true, message: '请输入房屋ID', trigger: 'blur' }]
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    const params = Object.fromEntries(
      Object.entries(filterParams.value).filter(([_, v]) =>
        v !== '' && v !== null && v !== undefined
      )
    );
    const response = await userList(params);
    if (response.data.code === 200) {
      users.value = response.data.data || [];
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error('请求失败:' + error.message);
  } finally {
    loading.value = false;
  }
};

// 编辑用户
const handleEdit = (user) => {
  editUser.value = { ...user };
  editDialogVisible.value = true;
};

// 提交编辑用户
const submitEditUser = async () => {
  try {
    const response = await userUpdate(editUser.value);
    if (response.data.code === 200) {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      fetchUsers();
    } else {
      ElMessage.error('修改失败:' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('请求失败:' + error.message);
  }
};

// 删除用户
const handleDelete = async (email) => {
  try {
    await ElMessageBox.confirm('确定删除该用户？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const response = await userDel({ email });
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      users.value = users.value.filter((user) => user.email !== email);
    } else {
      ElMessage.error('删除失败:' + response.data.msg);
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('请求失败:' + error.message);
    }
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterParams.value = {
    username: '',
    email: '',
    roleId: null,
    houseId: null
  };
  fetchUsers();
};

onMounted(fetchUsers);
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 40px);
}

.header {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  .filter-form {
    margin-left: 0;
  }
}

.table-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.el-table {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.el-tag {
  margin: 2px;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-form-item__label) {
  color: #666;
}
</style>